03 / 04

Show usage of call, apply bind.

We can use them to implement Method Borrowing, Function Composition and Chaining, Function with Varying Arguments, Setting Context for Callbacks, Using Functions as Constructors.

Function Composition and Chaining: call and apply can be used to chain and compose functions. By setting the context to the result of one function, you can chain another function call to operate on that context.

javascript

Method Borrowing: When you have a method defined on one object, but you want to use it on another object that doesn't have that method, you can use call or apply to borrow the method from the first object and execute it in the context of the second object.

javascript

Function with Varying Arguments: When a function can accept a variable number of arguments, you can use apply to pass an array-like object as arguments to the function.

javascript

Setting Context for Callbacks: When you pass a function as a callback to another function, the context can change. Using bind, we can ensure that the callback function maintains the desired context.

javascript

Using Functions as Constructors: In JavaScript, functions can be used as constructors to create objects. call and apply can be used to set the newly created object as the context while initializing properties.

javascript